<template>
  <div class="dashboard">
    <!-- 系统公告和天气信息 -->
    <el-row :gutter="20" class="info-section">
      <el-col :xs="24" :sm="12" :md="8" :lg="8">
        <el-card class="dashboard-card" header="系统公告">
          <div class="notice-list">
            <div v-for="notice in systemNotices" :key="notice.id" class="notice-item">
              <el-tag :type="notice.type" size="small">{{ notice.category }}</el-tag>
              <span class="notice-title">{{ notice.title }}</span>
              <span class="notice-time">{{ notice.time }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="8" :lg="8">
        <el-card class="dashboard-card" header="天气信息">
          <div class="weather-info">
            <div class="weather-main">
              <div class="weather-icon">
                <el-icon><Sunny /></el-icon>
              </div>
              <div class="weather-text">
                <div class="temperature">{{ weatherInfo.temperature }}°C</div>
                <div class="weather-desc">{{ weatherInfo.description }}</div>
                <div class="location">{{ weatherInfo.location }}</div>
              </div>
            </div>
            <div class="weather-details">
              <div class="detail-item">
                <span>湿度：{{ weatherInfo.humidity }}%</span>
              </div>
              <div class="detail-item">
                <span>风速：{{ weatherInfo.windSpeed }} km/h</span>
              </div>
              <div class="detail-item">
                <span>能见度：{{ weatherInfo.visibility }} km</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <el-card class="dashboard-card" header="运行状态">
          <div class="system-status">
            <div class="status-item">
              <span class="status-label">服务状态：</span>
              <el-tag type="success" size="small">运行正常</el-tag>
            </div>
            <div class="status-item">
              <span class="status-label">数据库：</span>
              <el-tag type="success" size="small">连接正常</el-tag>
            </div>
            <div class="status-item">
              <span class="status-label">网络延迟：</span>
              <span class="status-value">{{ systemStatus.latency }}ms</span>
            </div>
            <div class="status-item">
              <span class="status-label">CPU使用率：</span>
              <el-progress :percentage="systemStatus.cpuUsage" size="small" />
            </div>
            <div class="status-item">
              <span class="status-label">内存使用：</span>
              <el-progress :percentage="systemStatus.memoryUsage" size="small" status="warning" />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="stat-card">
          <div class="stat-icon camera">
            <el-icon><Camera /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ cameraStats.total }}</div>
            <div class="stat-label">摄像头总数</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="stat-card">
          <div class="stat-icon online">
            <el-icon><VideoPlay /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ cameraStats.online }}</div>
            <div class="stat-label">在线设备</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="stat-card">
          <div class="stat-icon offline">
            <el-icon><VideoPause /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ cameraStats.offline }}</div>
            <div class="stat-label">离线设备</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="stat-card">
          <div class="stat-icon error">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ cameraStats.error }}</div>
            <div class="stat-label">故障设备</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 主要功能区域 -->
    <el-row :gutter="20" class="main-content">
      <!-- 设备状态监控 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
        <el-card class="dashboard-card" header="设备状态监控">
          <div class="device-monitor">
            <div class="device-item" v-for="camera in recentCameras" :key="camera.id">
              <div class="device-info">
                <div class="device-name">{{ camera.name }}</div>
                <div class="device-location">{{ camera.location }}</div>
              </div>
              <div class="device-status">
                <el-tag 
                  :type="getStatusType(camera.status)"
                  size="small"
                >
                  {{ getStatusText(camera.status) }}
                </el-tag>
              </div>
            </div>
          </div>
          <div class="card-footer">
            <el-button type="primary" text @click="goToCamera">查看全部</el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 快速操作 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
        <el-card class="dashboard-card" header="快速操作">
          <div class="quick-actions">
            <div 
              class="action-item"
              v-for="action in quickActions"
              :key="action.key"
              @click="handleQuickAction(action.key)"
            >
              <div class="action-icon">
                <el-icon><component :is="action.icon" /></el-icon>
              </div>
              <div class="action-text">{{ action.label }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 系统信息 -->
      <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
        <el-card class="dashboard-card" header="系统信息">
          <div class="system-info">
            <div class="info-item">
              <span class="info-label">当前用户：</span>
              <span class="info-value">{{ userName }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">用户角色：</span>
              <span class="info-value">{{ userRole }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">登录时间：</span>
              <span class="info-value">{{ formatDate(new Date()) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">系统版本：</span>
              <span class="info-value">v1.0.0</span>
            </div>
            <div class="info-item">
              <span class="info-label">服务状态：</span>
              <el-tag type="success" size="small">运行正常</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="dashboard-card" header="最近活动">
          <el-timeline>
            <el-timeline-item
              v-for="activity in recentActivities"
              :key="activity.id"
              :timestamp="activity.time"
              :type="activity.type"
            >
              <div class="activity-content">
                <div class="activity-title">{{ activity.title }}</div>
                <div class="activity-desc">{{ activity.description }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  ElRow,
  ElCol,
  ElCard,
  ElIcon,
  ElButton,
  ElTag,
  ElTimeline,
  ElTimelineItem,
  ElProgress
} from 'element-plus'
import {
  House,
  Camera,
  VideoPlay,
  VideoPause,
  Warning,
  MapLocation,
  User,
  Setting,
  Sunny
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { useCameraStore } from '@/stores/camera'

// Store
const authStore = useAuthStore()
const cameraStore = useCameraStore()
const router = useRouter()

// 响应式数据
const systemNotices = ref([
  {
    id: 1,
    title: '系统升级维护通知',
    category: '维护',
    type: 'warning',
    time: '2024-01-15'
  },
  {
    id: 2,
    title: '新增摄像头设备',
    category: '设备',
    type: 'success',
    time: '2024-01-14'
  },
  {
    id: 3,
    title: '安全检查提醒',
    category: '安全',
    type: 'danger',
    time: '2024-01-13'
  }
])

const weatherInfo = ref({
  temperature: 22,
  description: '晴朗',
  location: '唐山市',
  humidity: 65,
  windSpeed: 8,
  visibility: 15
})

const systemStatus = ref({
  latency: 28,
  cpuUsage: 45,
  memoryUsage: 62
})

const recentActivities = ref([
  {
    id: 1,
    title: '摄像头CAM001上线',
    description: '厂区入口摄像头重新连接成功',
    time: '2024-01-15 14:30',
    type: 'success'
  },
  {
    id: 2,
    title: '用户权限更新',
    description: '系统管理员更新了用户权限配置',
    time: '2024-01-15 13:45',
    type: 'primary'
  },
  {
    id: 3,
    title: '摄像头CAM003离线',
    description: '原料仓库摄像头连接中断，请检查网络',
    time: '2024-01-15 12:20',
    type: 'warning'
  }
])

const quickActions = [
  { key: 'video', label: '实时视频', icon: VideoPlay },
  { key: 'map', label: '电子地图', icon: MapLocation },
  { key: 'camera', label: '设备管理', icon: Camera },
  { key: 'user', label: '用户管理', icon: User },
  { key: 'settings', label: '系统设置', icon: Setting }
]

// 计算属性
const userName = computed(() => authStore.userName)
const userRole = computed(() => {
  const role = authStore.userRole
  return role === 'admin' ? '系统管理员' : '普通用户'
})

const cameraStats = computed(() => cameraStore.statusStats)
const recentCameras = computed(() => cameraStore.cameras.slice(0, 5))

// 方法
const getStatusType = (status: string) => {
  const types = {
    online: 'success',
    offline: 'info',
    error: 'danger'
  }
  return types[status as keyof typeof types] || 'info'
}

const getStatusText = (status: string) => {
  const texts = {
    online: '在线',
    offline: '离线',
    error: '故障'
  }
  return texts[status as keyof typeof texts] || '未知'
}

const formatDate = (date: Date) => {
  return date.toLocaleString('zh-CN')
}

const handleQuickAction = (key: string) => {
  const routes = {
    video: '/video/live',
    map: '/map',
    camera: '/camera',
    user: '/system/user',
    settings: '/system/role'
  }
  
  const route = routes[key as keyof typeof routes]
  if (route) {
    router.push(route)
  }
}

const goToCamera = () => {
  router.push('/camera')
}

// 初始化
onMounted(async () => {
  try {
    console.log('CameraStore:', cameraStore)
    await cameraStore.fetchCameraList()
  } catch (error) {
    console.error('Failed to fetch camera list:', error)
  }
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.dashboard-header {
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.info-section {
  margin-bottom: 20px;
}

.notice-list {
  max-height: 180px;
  overflow-y: auto;
}

.notice-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 12px;
}

.notice-item:last-child {
  border-bottom: none;
}

.notice-title {
  flex: 1;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.notice-time {
  color: #909399;
  font-size: 11px;
}

.weather-info {
  padding: 10px 0;
}

.weather-main {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}

.weather-icon {
  font-size: 32px;
  color: #f39c12;
}

.weather-text {
  flex: 1;
}

.temperature {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.weather-desc {
  color: #606266;
  font-size: 14px;
  margin: 4px 0;
}

.location {
  color: #909399;
  font-size: 12px;
}

.weather-details {
  display: grid;
  grid-template-columns: 1fr;
  gap: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #606266;
}

.system-status {
  padding: 10px 0;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 13px;
}

.status-label {
  color: #606266;
}

.status-value {
  color: #303133;
  font-weight: 500;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.camera { background: linear-gradient(45deg, #409eff, #67c23a); }
.stat-icon.online { background: linear-gradient(45deg, #67c23a, #85ce61); }
.stat-icon.offline { background: linear-gradient(45deg, #909399, #b1b3b8); }
.stat-icon.error { background: linear-gradient(45deg, #f56c6c, #f78989); }

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.main-content {
  margin-bottom: 20px;
}

.dashboard-card {
  height: 100%;
}

.dashboard-card :deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-weight: bold;
}

.device-monitor {
  min-height: 200px;
}

.device-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.device-item:last-child {
  border-bottom: none;
}

.device-info {
  flex: 1;
}

.device-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.device-location {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.card-footer {
  text-align: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
  gap: 16px;
  padding: 10px 0;
}

.action-item {
  text-align: center;
  padding: 16px 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-item:hover {
  background: #f8f9fa;
  transform: translateY(-2px);
}

.action-icon {
  font-size: 24px;
  color: #409eff;
  margin-bottom: 8px;
}

.action-text {
  font-size: 12px;
  color: #606266;
}

.system-info {
  padding: 10px 0;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 14px;
  color: #606266;
}

.info-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.activity-content {
  margin-left: 16px;
}

.activity-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.activity-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stat-card {
    padding: 16px;
  }
  
  .stat-icon {
    width: 48px;
    height: 48px;
    font-size: 20px;
  }
  
  .stat-number {
    font-size: 24px;
  }
  
  .quick-actions {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .action-item {
    padding: 12px 4px;
  }
}
</style>